package InetAddress;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * 需求：客户端发送一行，服务器接收一行，所以用if
 */
public class TCPServer {

    public static void main(String[] args) throws Exception {
        System.out.println("=======服务器端启动==========");
        //一个服务器端只需要对应一个线程池




        //1.注册端口
        ServerSocket ss = new ServerSocket(8888);

        while (true)
        {
            //2.开始等待客户端连接
            Socket accept = ss.accept();
            System.out.println(accept.getRemoteSocketAddress()+"上线了");
            new ServerReaderThread(accept).start();
        }
    }
}

class ServerReaderThread extends Thread{

    private Socket socket;
    public ServerReaderThread(Socket accept)

    {
        this.socket=accept;
    }

    @Override
    public void run() {
        try {
            InputStream ins = socket.getInputStream();        //字节输入流
            Reader rs = new InputStreamReader(ins);          //把字节输入流转换成字符输入流
            BufferedReader bs = new BufferedReader(rs);      //把字符输入流包装成缓冲字符输入流
            //6按照行读取消息
            String msg;   //读取一行消息
            while ((msg= bs.readLine())!=null)
            {
                System.out.println(socket.getRemoteSocketAddress()+"说："+msg);
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}

//线程池

/*

public class HandleSocketThreadPool{

    private ExecutorService executorService;
    public HandleSocketThreadPool (int maxPoolSize, int queueSize)//两个参数：最大线程数量，最大任务队列
    {
        this.executorService =new ThreadPoolExecutor(
                maxPoolSize,
                maxPoolSize,
                120L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(queueSize));

    }
    public void execute(Runnable task)
    {
        this.executorService.execute(task);
    }
}
*/
